package com.example.common.config.rabbit.ware;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>
 *
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
@Configuration
public class WareTransactionalConfig {

    public static final String DELAY_QUEUE = "stock.delay.queue";
    public static final String NORMAL_QUEUE = "stock.release.queue";

    public static final String DELAY_KEY = "stock.locked";
    public static final String NORMAL_KEY = "stock.release.#";

    /** 订单与库存的路由键 **/
    public static final String STOCK_RELEASE_KEY = "order.release.other";
    public static final String ORDER_STOCK_BINDING_KEY = "order.release.other.#";

    public static final String STOCK_EXCHANGE = "stock-event-exchange";

    @Value("${ware.queue.ttl}")
    public Integer ttl;

    /**
     * 创建死信队列
     *
     * @return  死信队列
     */
    @Bean(name = DELAY_QUEUE)
    public Queue stockDelayQueue () {
        return QueueBuilder.durable(DELAY_QUEUE)
                .withArgument("x-dead-letter-exchange", STOCK_EXCHANGE)
                .withArgument("x-dead-letter-routing-key", NORMAL_KEY)
                .withArgument("x-message-ttl", ttl)
                .build();
    }

    /**
     * 正常队列
     *
     * @return  正常对垒
     */
    @Bean(name = NORMAL_QUEUE)
    public Queue stockReleaseQueue () {
        return QueueBuilder.durable(NORMAL_QUEUE).build();
    }

    /**
     * 创建交换机
     *
     * @return  top 交换机
     */
    @Bean(name = STOCK_EXCHANGE)
    public Exchange stockEventExchange () {
        return ExchangeBuilder.topicExchange(STOCK_EXCHANGE).build();
    }


    /**
     * 创建死信队列与交换机的绑定关系
     *
     * @param release   死信队列
     * @param ex        交换机
     * @return          绑定关系
     */
    @Bean public Binding stockLockedBinding ( @Qualifier(DELAY_QUEUE) Queue release,
                                              @Qualifier(STOCK_EXCHANGE) Exchange ex) {
        return BindingBuilder.bind(release).to(ex).with(DELAY_KEY).noargs();
    }

    /**
     * 创建普通队列与交换机的绑定关系
     *
     * @param release   普通队列
     * @param ex        交换机
     * @return          绑定关系
     */
    @Bean public Binding stockReleaseBinding (@Qualifier(NORMAL_QUEUE) Queue release,
                                                  @Qualifier(STOCK_EXCHANGE) Exchange ex) {
        return BindingBuilder.bind(release).to(ex).with(NORMAL_KEY).noargs();
    }

}
